﻿using System.IO;

namespace avs2bdnxml_gui
{
    public class FileManagement
    {
        /// <summary>
        /// 删除一个目录（空或非空）
        /// 1.先删除该目录下的所有文件
        /// 2.再删除该目录下的所有子孙目录
        /// 3.最后删除该目录（已成为空目录）
        /// </summary>
        /// <param name="dirName">目录名</param>
        public static void RemoveDir(string dirName)
        {
            if (!Directory.Exists(dirName))
            {
                return;
            }

            var fileNames = Directory.GetFiles(dirName);
            var dirNames = Directory.GetDirectories(dirName);
            foreach (var fileName in fileNames)
            {
                File.Delete(fileName);
            }

            foreach (var dirName_ in dirNames)
            {
                RemoveDir(dirName_);
            }

            Directory.Delete(dirName);
        }

        /// <summary>
        /// 清空一个目录
        /// 1.删除所有的文件
        /// 2.清空所有的子孙目录
        /// 3.删除所有的子孙目录（已经成为空目录）
        /// </summary>
        /// <param name="dirName">目录名</param>
        public static void ClearDir(string dirName)
        {
            if (!Directory.Exists(dirName))
            {
                return;
            }

            var fileNames = Directory.GetFiles(dirName);
            var dirNames = Directory.GetDirectories(dirName);
            foreach (var fileName in fileNames)
            {
                File.Delete(fileName);
            }

            foreach (var dirName_ in dirNames)
            {
                ClearDir(dirName_);
                Directory.Delete(dirName_);
            }
        }

        /// <summary>
        /// 将一个目录下的内容拷贝到另一个目录下
        /// </summary>
        /// <param name="sourceDir"></param>
        /// <param name="targetDir"></param>
        public static void CopyDir(string sourceDir, string targetDir)
        {
            if (!Directory.Exists(targetDir))
            {
                Directory.CreateDirectory(targetDir);
            }

            var fileNames = Directory.GetFiles(sourceDir);
            var dirNames = Directory.GetDirectories(sourceDir);
            foreach (var fileName in fileNames)
            {
                File.Copy(fileName, targetDir + Path.DirectorySeparatorChar + Path.GetFileName(fileName), true);
            }

            foreach (var dirName_ in dirNames)
            {
                var splitStr = dirName_.Split(Path.DirectorySeparatorChar);
                CopyDir(dirName_, targetDir + Path.DirectorySeparatorChar + splitStr[splitStr.Length - 1]);
            }
        }
    }
}